<template>
	<div style="margin:16px auto; max-width: 960px; padding: 0 12px;">
		<a-card title="系统配置">
			<template #extra>
				<a-space>
					<a-input v-model:value="prefix" placeholder="按前缀筛选，如 site." style="width: 240px" />
					<a-button type="primary" @click="load">查询</a-button>
				</a-space>
			</template>
			<a-table :data-source="rows" :columns="columns" :row-key="rowKey" :pagination="false">
				<template #bodyCell="{ column, record }">
					<template v-if="column.key==='actions'">
						<a @click="openEdit(record)">编辑</a>
					</template>
				</template>
			</a-table>
		</a-card>

		<a-card title="新增/修改配置" style="margin-top: 16px;">
    			<a-form :model="form" :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }">
				<a-form-item label="Key"><a-input v-model:value="form.key" placeholder="如 site.title" /></a-form-item>
				<a-form-item label="Value"><a-input v-model:value="form.value" /></a-form-item>
				<a-form-item label="描述"><a-input v-model:value="form.description" /></a-form-item>
				<a-form-item :wrapper-col="{ offset: 5, span: 19 }"><a-button type="primary" @click="save">保存</a-button></a-form-item>
			</a-form>
		</a-card>

		<a-card title="SEO 与站点地图管理" style="margin-top: 16px;">
			<a-space style="margin-bottom: 16px;">
				<a-button type="primary" @click="handleGenerateSitemap" :loading="seoLoading">
					<template #icon><FileSearchOutlined /></template>
					生成站点地图
				</a-button>
				<a-button @click="handleClearSitemapCache" :loading="seoLoading">
					<template #icon><DeleteOutlined /></template>
					清除缓存
				</a-button>
				<a-button @click="handleSubmitSitemap" :loading="seoLoading">
					<template #icon><CloudUploadOutlined /></template>
					提交到搜索引擎
				</a-button>
			</a-space>
			<a-descriptions bordered :column="1">
				<a-descriptions-item label="站点地图地址">
					<a :href="sitemapUrl" target="_blank">{{ sitemapUrl }}</a>
				</a-descriptions-item>
				<a-descriptions-item label="Robots.txt">
					<a :href="robotsUrl" target="_blank">{{ robotsUrl }}</a>
				</a-descriptions-item>
				<a-descriptions-item label="说明">
					站点地图每天凌晨2点自动生成，每周一凌晨3点自动提交到搜索引擎。
					您也可以手动触发生成和提交操作。
				</a-descriptions-item>
			</a-descriptions>
		</a-card>

		<a-card title="缓存管理 (Redis)" style="margin-top: 16px;">
			<a-space style="margin-bottom: 12px;">
				<a-input v-model:value="pattern" placeholder="Key 模式，如 auth:* 或 *" style="width: 260px" />
				<a-button @click="ping">Ping</a-button>
				<a-button type="primary" @click="scan">扫描</a-button>
				<a-popconfirm title="确认按模式删除这些 Key？" @confirm="delKeys"><a-button danger>删除</a-button></a-popconfirm>
			</a-space>
			<a-list size="small" bordered :data-source="keys">
				<template #renderItem="{ item }">
					<a-list-item>{{ item }}</a-list-item>
				</template>
			</a-list>
		</a-card>
	</div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { message } from 'ant-design-vue'
import { FileSearchOutlined, DeleteOutlined, CloudUploadOutlined } from '@ant-design/icons-vue'
import { listConfigs, upsertConfig, scanCacheKeys, deleteCache, cachePing, type SystemConfigVO } from '@/api/admin/modules/system'
import { generateSitemap, clearSitemapCache, submitSitemap } from '@/api/admin'

const prefix = ref('')
const rows = ref<SystemConfigVO[]>([])
const columns = computed(() => [
	{ title: 'ID', dataIndex: 'id' },
	{ title: 'Key', dataIndex: 'configKey' },
	{ title: 'Value', dataIndex: 'configValue' },
	{ title: '描述', dataIndex: 'description' },
	{ title: '创建时间', dataIndex: 'createTime' },
	{ title: '操作', key: 'actions' }
])

function rowKey(r: any) { return r?.id ?? r?.configKey ?? Math.random().toString(36).slice(2) }

async function load() {
	const resp = await listConfigs(prefix.value || undefined)
	if ((resp as any).code === 0) {
		const data = (resp as any).data
		rows.value = Array.isArray(data) ? data : []
	}
}

const form = ref<{ key: string; value: string; description?: string }>({ key: '', value: '', description: '' })
function openEdit(row: SystemConfigVO) {
	form.value = { key: row.configKey, value: row.configValue || '', description: row.description }
}

async function save() {
	if (!form.value.key) { message.warning('请填写 Key'); return }
	const resp = await upsertConfig(form.value)
	if ((resp as any).code === 0) { message.success('已保存'); load() }
}

load()

// SEO 管理
const seoLoading = ref(false)
const sitemapUrl = computed(() => `${window.location.origin}/sitemap.xml`)
const robotsUrl = computed(() => `${window.location.origin}/robots.txt`)

async function handleGenerateSitemap() {
  try {
    seoLoading.value = true
    const response = await generateSitemap()
    if (response.success) {
      message.success('站点地图生成成功')
    } else {
      message.error(response.message || '生成失败')
    }
  } catch (error) {
    console.error('生成站点地图失败:', error)
    message.error('生成站点地图失败')
  } finally {
    seoLoading.value = false
  }
}

async function handleClearSitemapCache() {
  try {
    seoLoading.value = true
    const response = await clearSitemapCache()
    if (response.success) {
      message.success('缓存清除成功')
    } else {
      message.error(response.message || '清除失败')
    }
  } catch (error) {
    console.error('清除缓存失败:', error)
    message.error('清除缓存失败')
  } finally {
    seoLoading.value = false
  }
}

async function handleSubmitSitemap() {
  try {
    seoLoading.value = true
    const response = await submitSitemap()
    if (response.success) {
      message.success('站点地图提交成功')
    } else {
      message.error(response.message || '提交失败')
    }
  } catch (error) {
    console.error('提交站点地图失败:', error)
    message.error('提交站点地图失败')
  } finally {
    seoLoading.value = false
  }
}

// cache
const pattern = ref<string>('')
const keys = ref<string[]>([])
async function ping() {
    const resp = await cachePing()
    if ((resp as any).code === 0) message.success((resp as any).data ? 'Redis 正常' : 'Redis 不可用')
}
async function scan() {
    const resp = await scanCacheKeys(pattern.value || undefined, 200)
    if ((resp as any).code === 0) keys.value = (resp as any).data
}
async function delKeys() {
    const resp = await deleteCache(pattern.value || '*')
    if ((resp as any).code === 0) { message.success('已删除'); scan() }
}
</script>


